/**
 * @description 此组件为折线
 * @example
 * {idName： bar,
 *  xAxis: ['星期一', '星期二'],
 *  data: [
 *  {label: 'legend1', value:[{key: '星期一', value: 20},{key: '星期二', value: 20}]},
 * {label: 'legend2', value:[{key: '星期一', value: 20},{key: '星期二', value: 20}]}，
 * ]
 * }
 * @author gf
 * @todo 在不影响已有功能的情况下可增加props
 */

import React, { useEffect } from "react";
import * as echarts from "echarts";
import {
  axisLabelStyle,
  axisLineStyle,
  splitLineStyle,
  TOOLTIP_FONT_SIZE,
  yaxisLabelStyle,
  yaxisLineStyle,
} from "@/utils/echarts";
import useIoObserve from "@/hook/useIoObserve";
import * as _ from "lodash";

interface VProps {
  key: string; // 与x轴对应的值
  value: number; // y轴对应的值
}

export interface DataProps {
  label: string; // legend对应的中文
  value: VProps[];
}

export interface MultiLineProps {
  idName: string; // 每一个echarts图需要一个dom来创建实例，该id用来标识唯一dom
  xAxis: string[]; // x轴为字符串数组
  legend: string[];
  data: DataProps[];
  color?: string[];
  areaList?: any[];
  legendStyle?: Object;
  gridStyle?: Object;
  percent?: boolean;
  formatLen?: number;
  xAxisLabelProps?: any;
  yAxisLabelProps?: any;
  rightY?: string[];
  xAxisProps?: any;
  leftYName?: any;
  rightYName?: any;
  areaName?: any[]; // 面积图
  toolTipTitle?: string; // tooltip展示的title
  showRightY?: boolean;
  precisionY?:number
}

const MultiLine = (props: MultiLineProps) => {
  const {
    idName,
    xAxis,
    data,
    legend,
    color,
    areaList,
    legendStyle,
    gridStyle,
    percent,
    formatLen,
    xAxisLabelProps,
    yAxisLabelProps,
    rightY = [],
    xAxisProps,
    leftYName,
    rightYName,
    areaName,
    toolTipTitle,
    showRightY = true,
    precisionY
  } = props;

  const handleMultiLineData = (arr: any, str?: string) => {
    let res: any = [];
    arr.map((v) => {
      res.push([v.key, v.value]);
    });
    // console.log('res****************',res);
    return res;
  };

  // 处理分段背景
  const handlePiece = () => {
    // console.log(pieces);
    let res = areaList
      ?.sort(
        (a, b) =>
          new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
      )
      .map((v, index: number) => {
        return [
          {
            name: v.title,
            xAxis: v.startDate,
            itemStyle: {
              color: "rgba(253, 192, 113, 0.1)",
              // color: '#FDC071',
              // opacity:0.3
            },
            emphasis: {
              itemStyle: {
                color: "rgba(253, 192, 113, 0.2)",
              },
            },
          },
          { xAxis: v.endDate },
        ];
      });

    return res;
  };

  const options = {
    color,
    tooltip: {
      trigger: "axis",
      zIndex: 2,
      backgroundColor: "rgba(65,69,81,0.96)",
      extraCssText: "border-radius:2px",
      borderWidth: 0,
      textStyle: {
        fontSize: TOOLTIP_FONT_SIZE,
        color: "#fff",
        lineHeight: "28px",
      },
      valueFormatter: (value) => {
        return (
          (_.isNumber(value) ? value : "-") +
          (percent && _.isNumber(value) ? "%" : "")
        );
      },
      formatter: (params) => {
        let htmlStr =
          '<div class="echarts_tooltip"><p style="margin:0; text-align: left">' +
          (toolTipTitle || "") +
          params[0].axisValue +
          "</p>";
        for (let i = 0; i < params.length; i++) {
          htmlStr += `<div ><p style="margin-right:8px" title="${
            params[i].seriesName
          }">${params[i].marker + params[i].seriesName}</p><p class="value">${
            params[i].value[1]
          }${percent ? "%" : ""}</p></div>`;
        }
        htmlStr += "</div>";
        return htmlStr;
      },
    },
    xAxis: {
      type: "category",
      data: xAxis,
      boundaryGap: false,
      axisLabel: {
        ...axisLabelStyle(),
        fontSize: 8,
        ...xAxisLabelProps,
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLine: {
        ...axisLineStyle(),
        show: true,
      },
      splitLine: {
        show: false,
      },
      ...xAxisProps,
    },
    yAxis: [
      {
        type: "value",
        ...leftYName,
        axisTick: {
          show: false,
          alignWithLabel: true,
        },
        ...yaxisLineStyle(),
        axisLine: {
          ...yaxisLineStyle(),
          show: true,
        },
        axisLabel: {
          ...yaxisLabelStyle(percent ? "%" : "", precisionY),
          inside: false,
          fontSize: 8,
          ...yAxisLabelProps,
        },
        ...splitLineStyle(),
      },
      {
        ...rightYName,
        type: "value",
        position: "right",
        axisTick: {
          show: false,
          alignWithLabel: true,
        },
        ...yaxisLineStyle(),
        axisLine: {
          ...yaxisLineStyle(),
          show: true,
        },
        axisLabel: {
          ...yaxisLabelStyle(percent ? "%" : "", 0),
          inside: false,
          fontSize: 8,
        },
        ...splitLineStyle(),
        show: showRightY,
      },
    ],
    grid: {
      left: 15,
      right: 30,
      bottom: 10,
      top: 30,
      containLabel: true,
      ...gridStyle,
    },
    legend: {
      data: legend,
      icon: "rectangle",
      itemWidth: 11,
      itemHeight: 11,
      itemGap: 10,
      top: 5,
      formatter: (value) => {
        return value?.length > formatLen
          ? value.substr(0, formatLen) + "..."
          : value;
      },
      textStyle: {
        fontSize: 10,
        color: "#35425e",
        width: 48,
        height: 28,
        lineHeight: 28,
        padding: [0, 0, -3, 2],
      },
      ...legendStyle,
    },
    series: data.map((v) => {
      if (areaName?.includes(v.label)) {
        return {
          name: v.label,
          symbolSize: 0,
          data: handleMultiLineData(v.value),
          markArea: {
            data: !_.isEmpty(areaList) && handlePiece(),
          },
          type: "line",
          top: "22%",
          areaStyle: {
            opacity: 0.6,
          },
          lineStyle: {
            width: 0,
          },
          emphasis: {},
          yAxisIndex: 1,
        };
      }
      if (rightY.includes(v.label)) {
        return {
          name: v.label,
          symbolSize: 0,
          data: handleMultiLineData(v.value),
          markArea: {
            data: !_.isEmpty(areaList) && handlePiece(),
          },
          type: "line",
          top: "22%",
          lineStyle: {
            width: 1,
          },
          emphasis: {
            focus: "series",
            lineStyle: {
              width: 2,
            },
          },
          yAxisIndex: 1,
        };
      }
      return {
        name: v.label,
        symbolSize: 0,
        data: handleMultiLineData(v.value),
        markArea: {
          data: !_.isEmpty(areaList) && handlePiece(),
        },
        type: "line",
        top: "22%",
        lineStyle: {
          width: 1,
        },
        emphasis: {
          focus: "series",
          lineStyle: {
            width: 2,
          },
        },
        yAxisIndex: 0,
      };
    }),
  };

  const handleGenBar = () => {
    const dom = document.getElementById(idName);
    if (dom) {
      const myChart = echarts.init(dom);
      myChart.setOption(options);
    }
  };

  // 窗口大小改变
  const handleChangeSize = () => {
    setTimeout(() => {
      const dom = document.getElementById(idName);
      dom?.removeAttribute("_echarts_instance_");
      handleGenBar();
    }, 1);
  };

  useIoObserve(null, handleChangeSize, idName);

  useEffect(() => {
    handleGenBar();
    window.addEventListener("resize", handleChangeSize);
    return () => {
      const dom = document.getElementById(idName);
      dom?.removeAttribute("_echarts_instance_");
      window.removeEventListener("resize", handleChangeSize);
    };
  }, [data]);

  return (
    <div
      id={idName}
      style={{ width: "100%", height: "100%" }}
      onClick={(e) => {
        e.stopPropagation();
      }}
    ></div>
  );
};

export default MultiLine;
